package me.youline.dataServer.service.authentication;

import javax.annotation.PostConstruct;

import me.youline.dataServer.entity.UserToken;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

public class UserAuthenticationTokenRealm extends AuthorizingRealm {

	private static final String REAL_NAME = "youlime_token_shiro_realm";
	
	@Autowired
	private UserTokenService userTokenService;

	@PostConstruct
	private void initial() {

		this.setCredentialsMatcher(new CredentialsMatcher() {

			@Override
			public boolean doCredentialsMatch(AuthenticationToken token,
					AuthenticationInfo info) {
				SimpleAuthenticationInfo simple = (SimpleAuthenticationInfo) info;
				if (simple.getCredentials() == null) {
					return false;
				} else {
					UserToken userToken = (UserToken) simple.getCredentials();
					if (userToken.isExpired()) {
						return false;
					}
					return true;
				}
			}
		});

	}

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(
			PrincipalCollection principals) {
		// TODO need add
		return null;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken token) throws AuthenticationException {
		boolean isILegalToken = token == null || token.getPrincipal() == null;
		if (isILegalToken) {
			return null;
		}
		UserToken cachedToken = userTokenService.getUserTokenByTokenStr(token.getPrincipal().toString());
		if (cachedToken == null || cachedToken.isExpired()) {
			return null;
		} else {
			return new SimpleAuthenticationInfo(cachedToken.getToken(),
					cachedToken, REAL_NAME);
		}

	}


	@Override
	public boolean supports(AuthenticationToken token) {
		return token instanceof UserAuthenticationToken;
	}

	@Override
	public void setName(String name) {
		super.setName(REAL_NAME);
	}

}
